# Posting bot
# by Cee Pee

import os
import random
import re
import forumapi

def find_phrases():
	"""Returns all phrases files."""
	
	phrases = []
	for file in os.listdir("data"):
		m = re.match("^(.*)\.phrases$", file)
		if m:
			phrases.append(m.group(1))
	
	return(phrases)

def settings(settings):
	settings.add_option("--phrases", type="choice", choices=find_phrases(), help="phrases file", metavar="FILE")
	settings.add_option("-t", "--threads", type="list", help="thread IDs to work on", metavar="IDS")
	settings.add_option("-f", "--forum", type="int", help="forum ID to restrict the bot to", metavar="ID")
	settings.add_option("--tag", help="tag to use to search threads for", metavar="NAME")
	settings.add_option("--loop", type="bool", default=False, help="keep posting after the first thread")
	settings.add_option("--unique", type="bool", default=False, reverse={"help": "do not require unique threads (infinite loop)"}, help="require unique threads")
	settings.add_arg("text", optional=True, default="Post content", help="text to post")

def main(me, options, args):
	threads = []
	if options.threads:
		for thread in options.threads:
			try:
				threads.append(forumapi.Thread(me, id=int(thread)))
			except ValueError:
				pass
	elif options.forum:
		threads = forumapi.Forum.obj(me, options.forum).threads
	elif site.type == "vbulletin":
		if options.tag:
			threads = me.module.get_attr("Tag")(me, name=options.tag).threads
		else:
			threads = me.get_search_results(special="new")
	else:
		raise(forumapi.OptionError("Threads required."))
	
	phrases = []
	if options.phrases:
		phrases = open(forumapi.data_file(options.phrases, "phrases"), encoding="utf8").read().split("\n")
	
	first_loop = True
	while (options.loop or first_loop) and len(threads) > 0:
		first_loop = False
		
		if phrases:
			phrase = random.choice(phrases)
		else:
			phrase = args.text
		
		thread = random.choice(threads)
		if options.unique:
			threads.remove(thread)
		
		print("Thread ID: {0}".format(thread.id))
		print("Message: " + phrase)
		print(repr(me.make_post(phrase, t=thread)))

if __name__ == "__main__":
	forumapi.run(main, options=settings, supported_types=["vbulletin", "vanilla"])
